package com.hhz.springcloud.controller;

import com.hhz.springcloud.entites.CommonResult;
import com.hhz.springcloud.entites.Payment;
import com.hhz.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * 订单调用类
 *
 * @Author Rem
 * @Date 2020-03-09
 */

@Slf4j
@RestController
@RequestMapping("/order/payment")
public class OrderController {

    // private final static String PAYMENT_URL = "http://localhost:8001";
    //由单机换成地址指向 实现集群
    private final static String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancer loadBalancer;

    @Autowired
    private DiscoveryClient discoveryClient;


    //使用@requestBody.当请求content_type为：application/json类型的请求，数据类型为json时， json格式如下：{"aaa":"111","bbb":"222"}    一般post请求添加
    //不使用@requestBody.当请求content_type为：application/x-www-form-urlencoded类型的或multipart/form-data时，数据格式为aaa=111&bbb=222
    //@RequestParam注解接收的参数是来自于requestHeader中，即请求头。都是用来获取请求路径（url ）中的动态参数。也就是在url中，格式为xxx?username=123&password=456  一般get请求添加
    @GetMapping("/insert")
    public CommonResult insert(Payment payment) {
        log.info("插入数据库成功");
        return restTemplate.postForObject(PAYMENT_URL + "/payment/insert", payment, CommonResult.class);
    }


    /**
     * getForObject
     *
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public CommonResult<Payment> findById(@PathVariable Long id) {
        log.info("查询成功");
        return restTemplate.getForObject(PAYMENT_URL + "/payment/findById/" + id, CommonResult.class);
    }


    /**
     * 使用postForEntity
     *
     * @param payment
     * @return
     */
    @GetMapping("/insertEntity")
    public CommonResult insert2(Payment payment) {


        ResponseEntity<CommonResult> responseEntity = restTemplate.postForEntity(PAYMENT_URL + "/payment/insert", payment, CommonResult.class);

        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            log.debug("返回头信息:" + responseEntity.getHeaders());
            log.info("返回头信息:" + responseEntity.getHeaders());
            return responseEntity.getBody();
        } else {
            return new CommonResult(444, "操作失败");
        }
    }


    @GetMapping("/getEntity/{id}")
    public CommonResult<Payment> findById2(@PathVariable Long id) {

        ResponseEntity<CommonResult> responseEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/findById/" + id, CommonResult.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {

            log.info("返回状态码:" + responseEntity.getStatusCode());
            return responseEntity.getBody();
        } else {
            return new CommonResult(444, "操作失败");
        }
    }


    @GetMapping("/lb")
    public String getPaymentLb() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() <= 0) {
            return null;
        }

        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();

        return restTemplate.getForObject(uri + "/payment/serverPort", String.class);
    }


    /**
     * 测试链路
     * zipkin+sleuth
     *
     * @return
     */
    @GetMapping("/zipkin")
    public String paymentZipkin() {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/zipkin/", String.class);
    }


}
